import numpy as np
# 1. 参数计算对比
print("=== 参数量对比 ===")
# 全连接层：100x100图像连接到1个输出神经元
fc_params=100*100
print(f"全连接层权重数:{fc_params}")
# 3x3卷积核参数量
conv_params=3*3
print(f"3x3卷积核权重数:{conv_params}")
print(f"参数量减少:{fc_params//conv_params}倍")
# 2. 核心算法实现
def conv2d(x,w,b,stride=1,padding=0):
    #x:(batch, 通道_in, 高, 宽) w:(通道_out, 通道_in, 核高, 核宽)
    N,C_in,H_in,W_in = x.shape
    C_out,C_in,K_h,K_w = w.shape
    # 添加padding
    if padding > 0:
        x = np.pad(x,((0,0),(0,0),(padding,padding),(padding,padding)),'constant')
        H_in,W_in = x.shape[2],x.shape[3]
    # 计算输出尺寸
    H_out = (H_in - K_h) // stride + 1
    W_out = (W_in - K_w) // stride + 1
    # 初始化输出
    output = np.zeros((N,C_out,H_out,W_out))
    # 执行卷积
    for n in range(N):
        for c_out in range(C_out):
            for h in range(H_out):
                for w_idx in range(W_out):
                    h_start = h * stride
                    w_start = w_idx * stride
                    region = x[n,:,h_start:h_start+K_h,w_start:w_start+K_w]
                    output[n,c_out,h,w_idx] = np.sum(region * w[c_out]) + b[c_out]
    return output
# 3. 阶段一：特征检测验证
print("\n=== 阶段一：特征检测 ===")
# 创建中心十字图案
image_centered = np.array([[
    [0, 0, 0, 0, 0],
    [0, 0, 1, 0, 0],
    [0, 1, 1, 1, 0],
    [0, 0, 1, 0, 0],
    [0, 0, 0, 0, 0]
]], dtype=np.float32).reshape(1, 1, 5, 5)
# 设计十字检测卷积核
cross_kernel = np.array([[
    [0, 1, 0],
    [1, 1, 1],
    [0, 1, 0]
]], dtype=np.float32).reshape(1, 1, 3, 3)
bias = np.array([0.0])
print("原始图像:")
print(image_centered[0, 0])
# 执行卷积
result1 = conv2d(image_centered,cross_kernel,bias)
print("卷积结果:")
print(result1[0, 0])
# 4. 阶段二：平移不变性实验
print("\n=== 阶段二：平移不变性 ===")
# 创建平移后的十字图案
image_shifted = np.array([[
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 1, 0],
    [0, 0, 1, 1, 1],
    [0, 0, 0, 1, 0]
]], dtype=np.float32).reshape(1, 1, 5, 5)
print("平移后图像:")
print(image_shifted[0, 0])
# 使用相同卷积核
result2 = conv2d(image_shifted,cross_kernel,bias)
print("卷积结果:")
print(result2[0, 0])
# 结果对比
print("\n=== 结果对比 ===")
print("中心十字最大响应值:",np.max(result1))
print("平移十字最大响应值:",np.max(result2))
print("最大响应位置:")
print("中心十字:",np.unravel_index(np.argmax(result1),result1.shape))
print("平移十字:",np.unravel_index(np.argmax(result2),result2.shape))
